import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const timeOut = 24 * 3600
const request = axios.create({
  baseURL: '/api',
  timeout: 5000
})
function isCheckOut () {
  const newTime = Date.now()
  const timeStap = (newTime - store.getters.hrTime) / 1000
  return timeStap > timeOut
}
request.interceptors.request.use(
  config => {
    if (store.getters.token) {
      if (isCheckOut()) {
        Message.error('身份验证过期，请重新登录')
        // store.state.user.token = null
        store.dispatch('user/loginOutAction')
        router.push('/login')
        return
      }
    }
    config.headers.Authorization = store.getters.token
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

request.interceptors.response.use(
  response => {
    return response.data
    // const { success, data, message } = response.data
    // if (success) {
    //   return data
    // } else {
    //   Message.error(message)
    //   return Promise.reject(new Error(message))
    // }
  },
  err => {
    if (err.response.status === 401) {
      Message.error('身份验证过期，请重新登录')
      store.dispatch('user/logOutAction')
      router.push('/login')
    } else {
      Message.error(err.response.data)
    }
    return Promise.reject(err)
  }
)

export default request
